package io.bdmc.modules.job.task;

import io.bdmc.common.utils.Constant;
import io.bdmc.common.utils.EmailUtils;
import io.bdmc.common.utils.PDFReport;
import io.bdmc.modules.bss.entity.SmkPush;
import io.bdmc.modules.bss.service.ISmkAlarmService;
import io.bdmc.modules.bss.service.ISmkDeviceService;
import io.bdmc.modules.bss.service.ISmkPushService;
import io.bdmc.modules.bss.service.ISmkShopService;
import io.bdmc.modules.sys.entity.SysDept;
import io.bdmc.modules.sys.service.ISysDeptService;
import io.bdmc.modules.sys.service.SysUserService;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 测试定时任务(演示Demo，可删除)
 * 
 * testTask为spring bean的名称
 * 
 * @author huang lu
 * @email hlkyo@qq.com
 * @date 2016年11月30日 下午1:34:24
 */
@Component("testTask")
public class TestTask {
	private Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private ISmkPushService _pushSvs;

	@Autowired
	private ISmkAlarmService _alarmSvs;
	@Autowired
	private ISmkShopService _shopSvs;
	@Autowired
	private ISmkDeviceService _devSvs;

	@Autowired
	private SysUserService _userSvs;
	@Autowired
	private ISysDeptService _deptSvs;

	public <SysUser> void pdfReport(String params) {
		logger.info("我是带参数的pdfReport方法，正在被执行，参数为：" + params);
		QueryWrapper<SmkPush> w1 = new QueryWrapper<SmkPush>();
		w1.isNotNull("email");
		List<SmkPush> ps = _pushSvs.list(w1);
		for (SmkPush p : ps) {
			io.bdmc.modules.sys.entity.SysUser u = _userSvs.getById(p.getUserId());
			Long deptId = u.getDeptId();
			SysDept dep = _deptSvs.getById(deptId);
			Long shopCount = _shopSvs.countByDepId(deptId);// 商铺数
			Long devCount = _devSvs.selectCountByDepId(deptId);// 设备数
			
			LocalDateTime now = LocalDateTime.now();
			
			String str = String.format("截至%d年%d月%d日，%s智慧消防云平台共接入设备%d台，覆盖商铺%d间。", now.getYear(), now.getMonth().getValue(),
					1, dep.getName(), devCount, shopCount);
			String[] strs = new String[8];
			strs[0] = dep.getName();
			strs[1] = str;
			strs[2] = getAlarmCount(deptId);
			strs[3] = getAlarmDeptStr(deptId);
			strs[4] = getAlarmPlaceStr(deptId);
			strs[5] = getAlarmReasonStr(deptId);
			strs[6] = getHiddenAlarmDeptStr(deptId);
			strs[7] = getHiddenAlarmPlaceStr(deptId);
			String filename = u.getUsername() + now.plusMonths(-1).getMonth().getValue()+"月消防安全管理月报"+".pdf";
			PDFReport.generatePDF(strs,filename);
			EmailUtils.sendFileMail("消防安全管理月报", "请下载附件查看", p.getEmail(),filename);
		}
	}

	// public <SysUser> void test3(String params) {
	// 	logger.info("我是带参数的test3方法，正在被执行，参数为：" + params);
	// 	try {
	// 		Thread.sleep(1000L);
	// 	} catch (InterruptedException e) {
	// 		e.printStackTrace();
	// 	}
	// }

	// public void test2() {
	// 	logger.info("我是不带参数的test2方法，正在被执行");


	// }

	//获取报警统计
	private String getAlarmCount(Long deptId){
		Map<String, Object> alarms = _alarmSvs.homeAlarmSumByMonth(deptId, 1);// 报警统计 1代表上月，2上上月
		if(alarms==null){
			return "本月暂无报警。";
		}
		Long total = Long.valueOf(alarms.get("confirm").toString())
					+ Long.valueOf(alarms.get("unconfirm").toString());
			Long fireCount = Long.valueOf(alarms.get("fire_count").toString());
			
		Long hiddenAlarm = total - fireCount;
		String str2 = String.format(
			"本月平台接到告警处理共%d起，其中火警警报%d起，隐患警报%d起，其中包括%s起离线警报，"
					+ "%s起传感器故障，%s起拆除警报以及%s起低压警报。所有警报中，有%s起得到及时处理，而有%s起未被处理。",
			total, fireCount, hiddenAlarm, alarms.get("offline_count").toString(),
			alarms.get("error_count").toString(), alarms.get("integral_count").toString(),
			alarms.get("power_count").toString(), alarms.get("confirm").toString(),
			alarms.get("unconfirm").toString());
			return str2;
	}

	// 上月火宅部门分布情况
	private String getAlarmDeptStr(Long deptId) {
		List<Map<String, Object>> alarmDept = _alarmSvs.fireAlarmDeptSumByMonth(deptId, 1);
		String str3 = "";
		if (alarmDept.size() == 0)
			return "无火警";
		if (alarmDept.size() > 3) {
			int totalCount = 0;
			int threeCount = 0;
			for (Integer i = 0; i < alarmDept.size(); i++) {
				Integer c = Integer.valueOf(alarmDept.get(i).get("count").toString());
				if (i < 3) {
					threeCount += c;
				}
				totalCount += c;
			}
			str3 = String.format("在火警警报中，来自%s的%s起，%s的%s起，%s的%s起，合计%s起，共占月总报警量的%s。", alarmDept.get(0).get("name"),
					alarmDept.get(0).get("count"), alarmDept.get(1).get("name"), alarmDept.get(1).get("count"),
					alarmDept.get(2).get("name"), alarmDept.get(2).get("count"), threeCount+"",bs(threeCount, totalCount) + "%");
		} else {
			str3 = "在火警警报中,来自";// 测试镇的54起，南湾社区的38起，深圳市的34起";
			for (Map<String, Object> map : alarmDept) {
				str3 = str3 + map.get("name").toString() + map.get("count") + "起,";
			}
			str3+="其余未反馈。";
		}
		return str3;
	}

	// 上月或者场所分布情况
	private String getAlarmPlaceStr(Long deptId) {
		List<Map<String, Object>> alarmDept = _alarmSvs.fireAlarmPlaceSumByMonth(deptId, 1);
		String str = "";
		if (alarmDept.size() == 0)
			return str;
		if (alarmDept.size() > 3) {
			int totalCount = 0;
			int threeCount = 0;
			for (Integer i = 0; i < alarmDept.size(); i++) {
				Integer c = Integer.valueOf(alarmDept.get(i).get("count").toString());
				if (i < 3) {
					threeCount += c;
				}
				totalCount += c;
			}
			// 火警的发生集中在超市（73起），餐饮场所（65起），其他（58起），XX（XX起），共占报警量的xxx%
			String place0 =alarmDept.get(0).get("shop_place")==null?"未知": Constant.formateShopPlace(Integer.valueOf(alarmDept.get(0).get("shop_place").toString()));
			String place1 =alarmDept.get(1).get("shop_place")==null?"未知": Constant.formateShopPlace(Integer.valueOf(alarmDept.get(1).get("shop_place").toString()));
			String place2 =alarmDept.get(2).get("shop_place")==null?"未知": Constant.formateShopPlace(Integer.valueOf(alarmDept.get(2).get("shop_place").toString()));
			str = String.format("火警的发生集中在%s(%s起)，%s的%s起，%s的%s起，合计%s起，共占月总报警量的%s。",place0,
					alarmDept.get(0).get("count"),place1, alarmDept.get(1).get("count"),place2, alarmDept.get(2).get("count"),threeCount+"", bs(threeCount, totalCount) + "%");
		} else {
			str = "火警的发生集中在";
			for (Map<String, Object> map : alarmDept) {
				str = str + Constant.formateShopPlace(Integer.valueOf(map.get("shop_place").toString())) + map.get("count") + "起，";
			}
			str+="其余场所未反馈。";
		}
		return str;
	}

		// 上月火宅原因分布情况
		private String getAlarmReasonStr(Long deptId) {
			List<Map<String, Object>> alarmReason = _alarmSvs.fireAlarmReasonSumByMonth(deptId, 1);
			String str3 = "";
			if (alarmReason.size() > 3) {
				int totalCount = 0;
				int threeCount = 0;
				for (Integer i = 0; i < alarmReason.size(); i++) {
					Integer c = Integer.valueOf(alarmReason.get(i).get("count").toString());
					if (i < 3) {
						threeCount += c;
					}
					totalCount += c;
				}
				//火灾原因205起未知，2起明火走火，2起漏电，1起生产作业不慎。共占报警量的XXXX%
				String reason0 = alarmReason.get(0).get("shop_reason")==null?"未知":Constant.formAlarmReason(Integer.valueOf(alarmReason.get(0).get("shop_reason").toString()));
				String reason1 = alarmReason.get(1).get("shop_reason")==null?"未知":Constant.formAlarmReason(Integer.valueOf(alarmReason.get(1).get("shop_reason").toString()));
				String reason2 = alarmReason.get(2).get("shop_reason")==null?"未知":Constant.formAlarmReason(Integer.valueOf(alarmReason.get(2).get("shop_reason").toString()));
				str3 = String.format("火灾原因%s起%s，%s起%s，%s起%s，合计%s起，共占月总报警量的%s", alarmReason.get(0).get("count"),
				reason0, alarmReason.get(1).get("count"), reason1,alarmReason.get(2).get("count"), reason2,threeCount+"", bs(threeCount, totalCount) + "%");
			} else {
				str3 = "火灾原因";
				for (Map<String, Object> map : alarmReason) {
					String reason = map.get("shop_reason")==null?"未知":Constant.formAlarmReason(Integer.valueOf(map.get("shop_reason").toString()));
					str3 = str3  + map.get("count") + "起"+ reason+"，";
				}
				str3+="其余未反馈。";
			}
			return str3;
		}

		// 上月隐患部门分布情况
	private String getHiddenAlarmDeptStr(Long deptId) {
		List<Map<String, Object>> alarmDept = _alarmSvs.fireHiddenAlarmDeptSumByMonth(deptId, 1);
		String str3 = "";
		if (alarmDept.size() > 3) {
			int totalCount = 0;
			int threeCount = 0;
			for (Integer i = 0; i < alarmDept.size(); i++) {
				Integer c = Integer.valueOf(alarmDept.get(i).get("count").toString());
				if (i < 3) {
					threeCount += c;
				}
				totalCount += c;
			}
			str3 = String.format("在隐患警报中，来自%s的%s起，%s的%s起，%s的%s起，合计%s起，共占月总报警量的%s。", alarmDept.get(0).get("name"),
					alarmDept.get(0).get("count"), alarmDept.get(1).get("name"), alarmDept.get(1).get("count"),
					alarmDept.get(2).get("name"), alarmDept.get(2).get("count"), threeCount+"",bs(threeCount, totalCount) + "%");
		} else {
			str3 = "在隐患警报中，来自";// 测试镇的54起，南湾社区的38起，深圳市的34起";
			for (Map<String, Object> map : alarmDept) {
				str3 = str3 + map.get("name").toString() + map.get("count") + "起，";
			}
			str3+="其余未反馈。";
		}
		return str3;
	}

//发生的场所主要是餐饮场所（4起），XX（X起），其余场所未反馈

// 上月隐患场所分布情况
private String getHiddenAlarmPlaceStr(Long deptId) {
	List<Map<String, Object>> alarmDept = _alarmSvs.fireHiddenAlarmPlaceSumByMonth(deptId, 1);
	String str = "";
	if (alarmDept.size() == 0)
		return str;
	if (alarmDept.size() > 3) {
		int totalCount = 0;
		int threeCount = 0;
		for (Integer i = 0; i < alarmDept.size(); i++) {
			Integer c = Integer.valueOf(alarmDept.get(i).get("count").toString());
			if (i < 3) {
				threeCount += c;
			}
			totalCount += c;
		}
		// 火警的发生集中在超市（73起），餐饮场所（65起），其他（58起），XX（XX起），共占报警量的xxx%
		String place0 =alarmDept.get(0).get("shop_place")==null?"未知": Constant.formateShopPlace(Integer.valueOf(alarmDept.get(0).get("shop_place").toString()));
		String place1 =alarmDept.get(1).get("shop_place")==null?"未知": Constant.formateShopPlace(Integer.valueOf(alarmDept.get(1).get("shop_place").toString()));
		String place2 =alarmDept.get(2).get("shop_place")==null?"未知": Constant.formateShopPlace(Integer.valueOf(alarmDept.get(2).get("shop_place").toString()));
		str = String.format("隐患的发生的场所集中在%s(%s起)，%s的%s起，%s的%s起，合计%s起，共占月总报警量的%s。",place0,
				alarmDept.get(0).get("count"),place1, alarmDept.get(1).get("count"),place2, alarmDept.get(2).get("count"), threeCount+"",bs(threeCount, totalCount) + "%");
	} else {
		str = "隐患的发生的场所集中在";// 测试镇的54起，南湾社区的38起，深圳市的34起";
		for (Map<String, Object> map : alarmDept) {
			str = str + Constant.formateShopPlace(Integer.valueOf(map.get("shop_place").toString())) + map.get("count") + "起，";
		}
		str+="其余场所未反馈。";
	}
	return str;
}

	public int bs(int a, int b) {
		return (int) ((new BigDecimal((float) a / b).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) * 100);
	}
}
